package com.nba.common.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.nba.system.bean.TreeBean;
import com.nba.common.cache.GlobalCache;
import com.nba.common.exception.CustomException;
import com.nba.common.framework.ErrorCode;
import com.nba.common.form.RequestDataForm;
import com.nba.common.form.ResponseDataForm;
import com.nba.common.sqlparse.SqlResultForm;
import com.nba.common.utils.Environment;
import com.nba.common.utils.MapUtils;
import com.nba.system.cache.RolePrivCache;
import com.nba.system.cache.UrlExecSqlCache;
import com.nba.system.cache.UserPrivCache;

/**
 * 非分页sql,一般直接只针对一条语句查询
 * @author Jesse ajax Service
 */
@Service("ajaxService")
public class AjaxService extends AbstractService {
	public ResponseDataForm service(RequestDataForm requestDataForm) throws Exception {
		// 实现如下:
		ResponseDataForm rdf = new ResponseDataForm(); 
		rdf.setResult(ResponseDataForm.SESSFUL);
		Map<String, Object> urlSqlMap = requestDataForm.getUrlSqlMap();
		Map<String, String> simpleRequestMap = requestDataForm.getSimpleRequestMap();
		String userCode=requestDataForm.getUserSession().getUserCode();
		
		//判断是否去缓存取数据
		String urlType = MapUtils.getString(urlSqlMap, "url_type");
		if(StringUtils.isNotBlank(urlType) && "cache".equals(urlType)){
		    List<TreeBean> retList = new ArrayList<TreeBean>();
		    String cacheName = MapUtils.getString(urlSqlMap, "cache_name");
		    Map<String, Object> cacheMap = GlobalCache.getCache(Class.forName("com.nba.system.cache."+cacheName), Map.class);
		    String pid = simpleRequestMap.get("node");
		    List<TreeBean> treeList = (List<TreeBean>)cacheMap.get(pid);
		    
		    String filterPrivFlag = MapUtils.getString(urlSqlMap, "filter_priv");
		    if(!Environment.ADMIN_USER_CODE.equals(userCode)
		            && StringUtils.isNotBlank(filterPrivFlag) && "Y".equals(filterPrivFlag)){
		        //过滤权限begin
	            Map<String, List<String>> userPrivMap = GlobalCache.getCache(UserPrivCache.class, Map.class);
	            List<String> userPrivList = userPrivMap.get(requestDataForm.getUserSession().getUserId());
	            
	            for(TreeBean tb : treeList){
	                if(userPrivList!=null && userPrivList.contains(tb.getPrivId())){
	                	retList.add(tb);
	                }
	            }
		    }else{
		    	retList = treeList;
		    }
		    
		    String roleId=MapUtils.getString(simpleRequestMap, "roleId");//未角色授权模块
		    if(StringUtils.isNotBlank(roleId)){
		    	Map<String, Object> rolePrivMap = GlobalCache.getCache(RolePrivCache.class, Map.class);
		    	List<String> list = (List<String>)rolePrivMap.get(roleId);
		    	if(retList != null && !retList.isEmpty()){
			    	for(TreeBean tb: retList){
			    		if(list.contains(tb.getPrivId())){
			    			tb.setChecked(1);
			    		}else{
			    			tb.setChecked(0);
			    		}
			    	}
		    	}
		    }
		    rdf.setAjaxObject(retList);
		}else{
    		//正常读取
    		String urlId = MapUtils.getString(urlSqlMap, "url_id");
    		Map<String, Element> execSqlMap = GlobalCache.getCache(UrlExecSqlCache.class, Map.class);
    		if(!execSqlMap.containsKey(urlId)){
    			throw new CustomException(ErrorCode.SQL_IS_NULL);
    		}
    		String execSql = MapUtils.getString(execSqlMap, urlId);
    		logger.debug("\n\r\t 待解析的xml：" + execSql);
    		NodeList sqlNodes = execSqlMap.get(urlId).getChildNodes();//
    		Element element = null;
    		for (int i = 0; i < sqlNodes.getLength(); i++) {
    			Node child = sqlNodes.item(i);
    			if (child.getNodeType() != Node.ELEMENT_NODE)
    				continue;
    			element = (Element) child;
    			SqlResultForm srf = sqlParse.parseNode(element, simpleRequestMap, requestDataForm.getUserSession());
    			Object ajaxObject = null;
    			String resultType = element.getAttribute("resultType");
    			if("string".equals(resultType)) {
    			    logger.debug("sql============"+srf.getParsedSql());
    				ajaxObject = jdbcDao.queryForString(srf.getParsedSql(), srf.getValueList().toArray());
    				logger.debug("obj============"+ajaxObject);
    			} else if("map".equals(resultType)) {
    				logger.debug("sql============"+srf.getParsedSql());
    				ajaxObject = jdbcDao.queryForMap(srf.getParsedSql(), srf.getValueList().toArray());
    				logger.debug("obj============"+ajaxObject);
    			} else {
    				logger.debug("sql============"+srf.getParsedSql());
    				ajaxObject = jdbcDao.queryForList(srf.getParsedSql(), srf.getValueList().toArray());
    				logger.debug("obj============"+ajaxObject);
    			}
    			rdf.setAjaxObject(ajaxObject);
    		}
		}
		return rdf;
	}
}
